from config import config
from widgets.scriptWidgets.ScriptWidget import ScriptWidget
from PySide6.QtWidgets import QLabel, QComboBox, QPushButton, QFileDialog
from PySide6.QtGui import QPixmap
from enums.WidgetType import WidgetType
from enums.ZhButtonType import ZhButtonType
from enums.ButtonType import ButtonType
from widgets.scriptWidgets.ScriptInput import ScriptInput
from util.Mouse import MouseUtil
from PIL import ImageGrab, ImageQt
import time
import os.path as ospath
import shutil


class ClickPic(ScriptWidget):
    def __init__(self, widgetType, initType=None):
        super().__init__(widgetType)
        self.picPath = ospath.join(
            config.SCRIPT_PIC_RECOGNITION_PIC_PATH,
            str(int(round(time.time() * 1000))) + '.png'
        )
        self.initType = initType

        self.labTitle = QLabel(self)
        if widgetType == WidgetType.CLICK_PIC:
            self.labTitle.setText('单击图片:')
        elif widgetType == WidgetType.DOUBLE_CLICK_PIC:
            self.labTitle.setText('双击图片:')

        self.labTitle.setToolTip('在指定区域内识别并单击图片')

        self.labTitle.setFixedSize(55, self.lineHeight)
        self.addWidget(self.labTitle)

        self.newLineSpaceWidth = self.labTitle.width() + self.intervalX

        # x
        self.inputX = ScriptInput(self, 'x')
        self.inputX.text = 0
        self.addWidget(self.inputX)

        # y
        self.inputY = ScriptInput(self, 'y')
        self.inputY.text = 0
        self.addWidget(self.inputY)

        # buttonType
        self.comButtonType = QComboBox(self)
        self.comButtonType.addItems(ZhButtonType.values())
        self.comButtonType.setCurrentText(ZhButtonType.values()[0])
        self.addWidget(self.comButtonType)

        if initType == 'edit' or initType == 'create':
            self.addOperate()

        # 宽
        self.inputWidth = ScriptInput(self, '宽')
        self.inputWidth.text = 0
        self.addWidget(self.inputWidth)

        # 高
        self.inputHeight = ScriptInput(self, '高')
        self.inputHeight.text = 0
        self.addWidget(self.inputHeight)

        self.btnTrack = QPushButton(self)
        self.btnTrack.setText('选择区域')
        self.btnTrack.clicked.connect(self.chooseArea)
        self.addWidget(self.btnTrack)

        self.newLine()
        # 图片
        self.labImgTitle = QLabel('图片', self)
        self.labImgTitle.setFixedSize(30, self.lineHeight)
        self.addWidget(self.labImgTitle)

        self.labImg = QLabel(self)
        self.labImg.setFixedSize(self.lineHeight, self.lineHeight)
        self.labImg.setStyleSheet(
            "QLabel{background:white;}"
        )
        self.addWidget(self.labImg)

        self.btnChoosePic = QPushButton(self)
        self.btnChoosePic.setText('选择图片')
        self.btnChoosePic.clicked.connect(self.choosePic)
        self.addWidget(self.btnChoosePic)

        self.btnGrab = QPushButton(self)
        self.btnGrab.setText('截取屏幕')
        self.btnGrab.clicked.connect(self.startGrab)
        self.addWidget(self.btnGrab)

    def choosePic(self):
        imgName, imgType = QFileDialog.getOpenFileName(
            self, "选择图片", "",
            "Image Files (*.png *.jpeg *.bmp);;All Files(*)")
        if imgName is None:
            return

        # 将需要识别的图片保存到应用内部存储地址
        shutil.copy(imgName, self.picPath)

        self.labImg.setPixmap(QPixmap(imgName).scaled(self.labImg.width(), self.labImg.height()))

    def onMouseClick(self, x, y, width, height, button):
        self.inputX.text = int(x)
        self.inputY.text = int(y)
        self.inputWidth.text = width
        self.inputHeight.text = height

    def chooseArea(self):
        MouseUtil.listenArea(self.onMouseClick)

    def grabScreen(self, x, y, width, height, button):
        left = x
        top = y
        right = x + width
        bottom = y + height
        # 将需要识别的图片保存到应用内部存储地址
        recoImg = ImageGrab.grab(bbox=(left, top, right, bottom))
        recoImg.save(self.picPath)
        self.labImg.setPixmap(ImageQt.toqpixmap(recoImg))

    def startGrab(self):
        MouseUtil.listenArea(self.grabScreen)

    @property
    def data(self):
        zhType = ZhButtonType(self.comButtonType.currentText())
        buttonType = ButtonType[zhType.name].value
        return {
            'type': self.type.value,
            'x': int(self.inputX.text),
            'y': int(self.inputY.text),
            'width': int(self.inputWidth.text),
            'height': int(self.inputHeight.text),
            'button': buttonType,
            'pic': self.picPath,
            'enable': self.switchEnable.isChecked()
        }

    @data.setter
    def data(self, data):
        self.inputX.text = str(data['x'])
        self.inputY.text = str(data['y'])
        self.inputWidth.text = str(data['width'])
        self.inputHeight.text = str(data['height'])
        self.comButtonType.setCurrentText(ZhButtonType[data['button'].upper()].value)
        self.labImg.setPixmap(QPixmap(data['pic']))
        self.picPath = data['pic']
